<script setup lang="ts">
import { ref, reactive, computed, onBeforeUnmount } from 'vue';
// import { PostPhoneLogin, PostLogin } from '@/apis/modules/login/index.ts';
interface PhoneForm {
  sms: string;
  phone: string;
  code: string;
}

// 60秒倒计时
let timeoutTimer: number;
// 每秒数字减一
let intervalTimer: number;
// 倒计时秒数
const count = ref(10);

// 收集表单数据
const phoneLoginForm = reactive<PhoneForm>({
  sms: '86',
  phone: '',
  code: '',
});

// 地区号码前缀数据
const smsOptions = [
  {
    text: '中国大陆',
    value: '86',
  },
  {
    text: '中国香港特别行政区',
    value: '852',
  },
  {
    text: '中国澳门特别行政区',
    value: '853',
  },
  {
    text: '中国台湾',
    value: '886',
  },
  {
    text: '美国',
    value: '1',
  },
  {
    text: '澳大利亚',
    value: '61',
  },
];

// 控制注册登录按钮的加载状态
const loginLoading = ref(false);
// 控制地区号码前缀选择区域的显示与隐藏
const smsShow = ref(false);
// 计算发送验证码的按钮是否禁用
const sendCodeBtnIsDisabled = computed(() => {
  return phoneLoginForm.phone.length === 0;
});

// 控制验证码发送按钮的加载状态
const sendCodeLoading = ref(false);

// 监听地区号码前缀按钮的点击事件
const handleClickSMS = () => {
  // 展示地区号码选择区
  smsShow.value = true;
  // 点击其他区域将隐藏选择区
  document.onclick = function () {
    smsShow.value = false;
    document.onclick = null;
  };
};

// 监听地区号码前缀点击事件
const handleClickSMSItem = (val: string) => {
  // 表单数据 sms赋值
  phoneLoginForm.sms = val;
  // sms选择区域隐藏
  smsShow.value = false;
};

// 监听手机号输入事件
const handleInputPhone = () => {
  phoneLoginForm.phone = phoneLoginForm.phone.replace(/[^\d]/g, '');
};

// 监听发送验证码按钮的点击事件
const handleClickSendCode = async () => {
  // 验证是否合法手机号
  let reg;
  if (phoneLoginForm.sms === '86') {
    reg = /^1[3,4,5,6,7,8,9][0-9]{9}$/;
  } else {
    reg = /^1[\d]{10,14}$/;
  }
  // 校验不通过
  if (!reg.test(phoneLoginForm.phone)) {
    // console.log('手机号格式错误');
    ElMessage.error('手机号格式错误');
    return;
  }
  // 获取验证码输入框dom元素
  const codeInputEl = document.querySelector('#code') as HTMLInputElement;
  // 验证码输入框获得焦点
  codeInputEl.focus();
  // 清空验证码输入框中的值
  phoneLoginForm.code = '';

  // 按钮进入加载状态
  sendCodeLoading.value = true;
  // 初始化倒计时秒数
  count.value = 10;
  // 进行倒计时
  intervalTimer = setInterval(() => {
    // 更新倒数数字
    count.value--;
    console.log(count.value);
  }, 1000);
  // 等待倒计时结束
  timeoutTimer = setTimeout(() => {
    // 按钮结束加载状态 进入可点击状态
    sendCodeLoading.value = false;
    // 取消设置的重复定时任务
    clearInterval(intervalTimer);
  }, 10000);

  // await PostLogin({ phoneNumber: phoneLoginForm.phone, type: 'login' });
};

// 监听注册登录按钮的点击事件
const handleClickLogin = async () => {
  if (phoneLoginForm.phone.length == 0) {
    ElMessage.error('请输入手机号');
    (document.querySelector('#phone') as HTMLInputElement).focus();
    return;
  }

  if (phoneLoginForm.code.length == 0) {
    ElMessage.error('请输入验证码');
    (document.querySelector('#code') as HTMLInputElement).focus();
    return;
  }
  loginLoading.value = true;
  // const { message, code } = await PostPhoneLogin({
  // 	phoneNumber: phoneLoginForm.phone,
  // 	validate: phoneLoginForm.code,
  // });
  // if (code === 200) {
  // 	ElMessage({
  // 		message: message,
  // 		type: 'success',
  // 	});
  // } else {
  // 	ElMessage.error(message);
  // }

  setTimeout(() => {
    loginLoading.value = false;
  }, 1500);
};

// 组件卸载前
onBeforeUnmount(() => {
  console.log('unmount');
  // 取消设置的重复定时任务
  clearInterval(intervalTimer);
  // 取消设置的定时任务
  clearTimeout(timeoutTimer);
});
</script>

<script lang="ts">
export default {
  name: 'PhoneForm',
};
</script>

<template>
  <form>
    <div class="flex flex-col rounded-lg" style="border: 1px solid rgb(226 232 240)">
      <div
        class="relative flex items-center justify-center gap-2 border-b border-solid border-slate-200 px-4 py-3"
      >
        <div
          class="flex cursor-pointer select-none items-center justify-center"
          @click.stop="handleClickSMS"
        >
          <span class="w-11">+{{ phoneLoginForm.sms }}</span>
          <el-icon class="w-3 cursor-pointer select-none">
            <ArrowDown />
          </el-icon>
        </div>
        <div class="flex flex-1 items-center justify-center">
          <input
            type="text"
            class="flex-1 bg-transparent"
            id="phone"
            name="phone"
            maxlength="15"
            placeholder="请输入手机号"
            v-model="phoneLoginForm.phone"
            @input="handleInputPhone"
          />
          <el-divider direction="vertical" />
          <el-button
            link
            type="primary"
            :disabled="sendCodeBtnIsDisabled"
            @click="handleClickSendCode"
            :loading="sendCodeLoading"
            class="w-[120px]"
          >
            获取验证码
            <span v-show="sendCodeLoading">({{ count }})</span>
          </el-button>
        </div>

        <div
          id="sms-select"
          class="absolute left-0 top-[100%] h-[200px] w-[220px] rounded-md border-t border-solid border-slate-200 bg-white py-2 shadow-md"
          v-show="smsShow"
        >
          <el-scrollbar>
            <div
              class="flex cursor-pointer select-none items-center justify-between gap-1 px-3 py-2 text-sm hover:bg-slate-100"
              v-for="sms in smsOptions"
              :key="sms.value"
              @click.stop="handleClickSMSItem(sms.value)"
              :class="sms.value == phoneLoginForm.sms ? 'sms-active' : ''"
            >
              <span :title="sms.text" class="flex-1 truncate">
                {{ sms.text }}
              </span>
              <span>+{{ sms.value }}</span>
            </div>
          </el-scrollbar>
        </div>
      </div>

      <div class="flex items-center justify-center px-4 py-3">
        <label for="code" class="w-11 select-none">验证码</label>
        <input
          type="text"
          class="ml-5 flex-1 bg-transparent"
          id="code"
          name="code"
          placeholder="请输入验证码"
          v-model="phoneLoginForm.code"
        />
        <div class="flex"></div>
      </div>
    </div>

    <div class="mt-8 flex items-center justify-center gap-2">
      <el-button
        class="w-[50%] text-sm"
        size="large"
        type="primary"
        @click="handleClickLogin"
        :loading="loginLoading"
      >
        登录/注册
      </el-button>
    </div>
  </form>
</template>

<style scoped>
.sms-active {
  color: #409ef4;
}

/* 媒体查询 */

/* 移动端 */
@media screen and (width <= 767px) {
}

/* 平板竖版 */
@media screen and (width >= 768px) and (width <= 991px) {
}

/* 平板横版 */
@media screen and (width >= 992px) and (width <= 1199) {
}

/* PC电脑端 */
@media screen and (width >= 1200px) {
}
</style>
